//
//  SYS_MessageStoreListVC.m
//  System_App
//
//  Created by 魏配军 on 2017/12/4.
//  Copyright © 2017年 czy001. All rights reserved.
//

#import "SYS_MessageStoreListVC.h"
#import "SYS_StoreListModel.h"
#import "SYS_SectionIndexView.h"
#import "SYS_StoreListCell.h"
#import "SYS_MessageStoreAddressListVC.h"
#import "SYS_MessageSendSearchVC.h"

@interface SYS_MessageStoreListVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    NSInteger page;
    BOOL isLast;
}
/*************搜索视图************/
@property (nonatomic, strong) SYS_SearchView *searchView;
/*************无数据视图************/
@property (nonatomic, strong) SYS_DisplayWithBlankView *alertView;
@property (nonatomic, strong) DSNewTableView *mainTableView;
@property (nonatomic, strong) NSMutableArray *dataListArray;
@property (nonatomic, strong) NSMutableArray *dataLetterArray;
@property (nonatomic, strong) NSMutableArray *totalDataArray;

@property (nonatomic, strong) SYS_SectionIndexView *sectionIndex;
@end

@implementation SYS_MessageStoreListVC

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavigationBar];
    [self initWithUI];

}

#pragma mark -- setter and getter
- (void)setNavigationBar{
    self.title = @"门店列表";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"SYS_Public_back" highImage:nil title:nil target:self action:@selector(backToPrevious)];
    self.view.backgroundColor = DGHColor(242, 242, 242);
}

#pragma mark   -------  UI  ---------
-(void) initWithUI
{
    _searchView = [[SYS_SearchView alloc] initWithFrame:CGRectMake(0, 10, SCREENWIDTH, 40)];
    _searchView.placeholder=@"请输入您要查找的门店";
    _searchView.isClickChange=NO;
    _searchView.inputTF.tag=99999;
    _searchView.inputTF.delegate=self;
    [self.view addSubview:_searchView];
    
    _mainTableView=[[DSNewTableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_searchView.frame)+10, SCREENWIDTH, SCREENHEIGHT-60-NavBarHeight) style:UITableViewStylePlain];
    _mainTableView.delegate=self;
    _mainTableView.dataSource=self;
    _mainTableView.backgroundColor=DSCOLOR_WHITE;
    _mainTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_mainTableView];
    
    page=1;
    _dataListArray=[NSMutableArray array];
    _dataLetterArray=[NSMutableArray array];
    _totalDataArray=[NSMutableArray array];
    [self requestStoreList:@""];

    _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        page=1;
        [self requestStoreList:@""];
        [_mainTableView.mj_header endRefreshing];
    }];
    
    _mainTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        if (_dataListArray.count % 20 == 0 && !isLast) {
            page++;
            [self requestStoreList:@""];
        }
        else
        {
            [MBProgressHUD showSuccess:@"当前页已是最新" toView:self.view];
        }
        [_mainTableView.mj_footer endRefreshing];
        
    }];
    
    _alertView=[[SYS_DisplayWithBlankView alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
    _alertView.photo.image=[UIImage imageNamed:@"message_mdbcz"];
    _alertView.title.text=@"你查找的门店不存在，请重新搜索~";
    _alertView.center=CGPointMake(_mainTableView.center.x, 140);
    _alertView.hidden=YES;
    [self.view addSubview:_alertView];
    
    
    //添加文本框通知中心
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gosave:) name:UITextFieldTextDidChangeNotification object:nil];
}

// 检测textfiled值得变化
- (void)gosave:(NSNotification *) Notification{
    UITextField * textField = Notification.object;
    
    if (textField.tag == 99999) {
        if (textField.text.length>0) {
            page=1;
            [self requestStoreList:textField.text];

        }else{
            [self requestStoreList:@""];

        }
    }
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    if (textField.tag == 99999) {
        if (textField.text.length>0) {
            page=1;
            [self requestStoreList:textField.text];
            
        }else{
            page=1;
            [self requestStoreList:@""];
            
        }
    }
    return YES;
}


#pragma mark   -----------请求门店列表数据----------
-(void) requestStoreList:(NSString *)searchText
{
    UITextField *textFiled=[self.view viewWithTag:99999];
    if (textFiled.text.length>0) {
        searchText=textFiled.text;
    }else{
        searchText=@"";
    }
    NSString *sessino=[SYS_LoginModel instance].sessionInfo.session;
    UICKeyChainStore *keychainStore = [UICKeyChainStore keyChainStore];
    NSString *pid = [keychainStore stringForKey:@"pid"];
    NSDictionary *parma=@{@"session":sessino,@"pageNumber":@(page),@"pageSize":@"20",@"pid":pid,@"search":searchText};
    [SYS_HttpUtility getStoreListRequest:parma success:^(id returnValue) {
        if (page==1) {
            [_dataListArray removeAllObjects];
            [_dataLetterArray removeAllObjects];
            [_totalDataArray removeAllObjects];
        }
        if ([returnValue[@"flag"] isEqualToString:@"true"]) {
            NSArray *listArray=returnValue[@"data"][@"list"];
            
            /*******************获取门店名称首字母↓↓↓↓↓↓↓↓↓***************/
            for (int index=0; index<listArray.count; index++) {
                SYS_StoreListModel *model=[SYS_StoreListModel mj_objectWithKeyValues:listArray[index]];
                model.firstLetter=[SYS_HelpModel transformMandarinToLatin:model.storeName];
                
                [_totalDataArray addObject:model];
                if (![_dataLetterArray containsObject:model.firstLetter]) {
                    [_dataLetterArray addObject:model.firstLetter];
                }
            }
            /*******************获取门店名称首字母↑↑↑↑↑↑↑↑↑***************/
//
//            NSArray *resultkArrSort = [_dataLetterArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//
//                return [obj1 compare:obj2 options:NSNumericSearch];
//            }];
//            _dataLetterArray=[NSMutableArray arrayWithArray:resultkArrSort];
//
//            /*******************每个字母下的门店数组↓↓↓↓↓↓↓↓↓***************/
//            [_dataListArray removeAllObjects];
//            for (int i = 0; i < _dataLetterArray.count; i++) {
//                NSMutableArray *array = [NSMutableArray new];
//                NSString *title = _dataLetterArray[i];
//                for (int j = 0; j < _totalDataArray.count; j++) {
//                    SYS_StoreListModel *model = _totalDataArray[j];
//                    if ([title isEqualToString:model.firstLetter]) {
//                        [array addObject:model];
//                    }
//                }
//                if (array.count>0) {
//                    [_dataListArray addObject:array];
//                }
//            }
//            /*******************每个字母下的门店数组↑↑↑↑↑↑↑↑↑***************/
//
//            _sectionIndex = [[SYS_SectionIndexView alloc] initWithFrame:CGRectMake(SCREENWIDTH - 30, (SCREENHEIGHT-364)/2, 30, 300) indexArray:_dataLetterArray];
//            _sectionIndex.backgroundColor = [UIColor clearColor];
//            [self.view addSubview:_sectionIndex];
//
//            [_sectionIndex selectIndexBlock:^(NSInteger section) {
//                [_mainTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section] animated:NO scrollPosition:UITableViewScrollPositionTop];
//            }];
            if (page>0 && listArray.count == 0) {
                isLast=YES;
            }
            _alertView.hidden=_totalDataArray.count?YES:NO;
            [_mainTableView reloadData];
            
        }else{
            [MBProgressHUD showSuccess:returnValue[@"exp"] toView:self.view];
        }
    } failure:^{
        RequestFailure;
    }];
    
}

#pragma mark  ----------UITableViewDelegate,UITableViewDataSource------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//    return _dataLetterArray.count;
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    NSArray *arr=_dataListArray[section];
//    return arr.count;
    return _totalDataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SYS_StoreListCell *cell = [[SYS_StoreListCell alloc]initWithTableView:tableView reuseId:@"SYS_StoreListCell"];
//    NSArray *arr=_totalDataArray[indexPath.section];
    SYS_StoreListModel *model=_totalDataArray[indexPath.row];
    cell.model=model;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
//    return 20;
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

//-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    
////        NSArray *array = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z"];
//    
//    UIView *bacview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 20)];
//    bacview.backgroundColor = DGHColor(248, 248, 248);
//    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(14, 0, 100, 20)];
//    titleLabel.text = _dataLetterArray[section];
//    titleLabel.textColor = DGHColorAlpha(100, 100, 100, 1);
//    titleLabel.font = [UIFont systemFontOfSize:14];
//    [bacview addSubview:titleLabel];
//    return bacview;
//}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SYS_MessageStoreAddressListVC *vc=[SYS_MessageStoreAddressListVC new];
//    NSArray *arr=_dataListArray[indexPath.section];
    SYS_StoreListModel *model=_totalDataArray[indexPath.row];
    vc.storeId=model.storeId;
    [self.navigationController pushViewController:vc animated:YES];
    
//    [self.navigationController pushViewController:[SYS_MessageSendSearchVC new] animated:YES];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

- (void)backToPrevious
{
    [self.navigationController popViewControllerAnimated:YES];
}






@end
